<?php
class Binhluan_model extends CI_Model {

    function __construct()
    {
    	// Call the Model constructor
        parent::__construct();
        $this->load->database();
    }
   
    function getBinhluan() {
    	//$this->load->database();
    	$sql = "SELECT bl.mabinhluan, bl.noidung, tk.tendangnhap, sp.tensanpham, DATE_FORMAT(bl.NgayDang, '%Y-%m-%d' ) AS ngaydang from binhluan bl, taikhoan tk, nguoidanhgia n, sanpham sp where bl.masanpham = sp.masanpham  and bl.manguoidanhgia = n.manguoidanhgia and n.mataikhoan = tk.mataikhoan";
    	return $this->db->query($sql)->result_array();
    }
	
    function xoaBinhluan($mabinhluan)
    {
    	$sql = "delete from binhluan where mabinhluan = $mabinhluan";
    	return $this->db->query($sql);
    }
    
	function getSoBL($tk){
		for($i=0; $i<count($tk); $i++){
			$sql = "SELECT count(MaBinhLuan) as SoBL FROM binhluan bl, nguoidanhgia ndg where ndg.manguoidanhgia = bl.manguoidanhgia and ndg.mataikhoan = ?";
			$res = $this->db->query($sql, array($tk[$i]['MaTaiKhoan']))->result_array();
			$sosanpham[$i] = $res[0]['SoBL'];
		}
		
		return $sosanpham;
	}
    
    function laybinhluantheomasp($masp)
    {
        $query = "select taikhoan.MaTaiKhoan, MaSanPham, binhluan.MaNguoiDanhGia, AnhDaiDien, DATE_FORMAT(NgayDang, '%d-%m-%Y' ) AS NgayDang, NoiDung, TenDangNhap
        from binhluan, nguoidanhgia, taikhoan 
        where MaSanPham = ?
        and binhluan.MaNguoiDanhGia = nguoidanhgia.MaNguoiDanhGia 
        and taikhoan.MaTaiKhoan = nguoidanhgia.MaTaiKhoan";
        return $this->db->query($query, array($masp))->result_array();
    }
    
    function thembinhluan($masanpham, $manguoidanhgia, $noidung)
    {
        $query = "insert into binhluan values(null, ?, ?, now() ,?)";
        return $this->db->query($query, array($masanpham, $manguoidanhgia, $noidung));
    }
}